# -*- coding: utf-8 -*-
"""* =====================================================
 * Copyright © hk. 2022-2025. All rights reserved.
 * File name: note_process.py
 * Author   : 上上签
 * Date     : 2023-07-04
 * Version  : 
 * Description: 
 * ======================================================
"""
import os
import sys
from urllib.parse import quote

def web_str2url(path_str, web_root_path="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/"):
    encod_path = quote(path_str, safe="?/:=.#&") # 这些特殊字符也可不处理
    return web_root_path + encod_path            # 返回一个拼接了完整图片路径的编码后的链接

if __name__ == "__main__":
    # 接收从shell传过来的参数 
    local_note_path = sys.argv[1]
    remote_note_path = sys.argv[2]
    note_relative_path = sys.argv[3]
    note_name = sys.argv[4]
    # 拼接两个包含路径的文件名，并打开这两个文件
    # local_file_name = os.path.join(local_note_path, note_name)
    # remote_file_name = os.path.join(remote_note_path, note_name)
    local_file_name = local_note_path + "/" + note_name
    remote_file_name = remote_note_path + "/" + note_name
    print("### python is processing %s" %(local_file_name))

    fp_file_local = open(local_file_name, "r", encoding='utf-8')
    fp_file_remote = open(remote_file_name, "w", encoding='utf-8')

    # 拼接源字符串和目标字符串
    new_line = []
    source_str_path = note_name.split(".")[0] + "/img/"
    source_str = note_relative_path + "/" + source_str_path
    # print(source_str_path) # 要匹配的原始字符串
    target_str = ""
    picture_head_src = "<!-- Photo: none -->"
    picture_head = ""
    line = fp_file_local.readline()
    line_num = 0 # 记录行号
    while line:
        line_num += 1
        # 处理图片链接
        index = line.find(source_str_path)
        if index != -1: # 此行中包含的有要查询的字符串
            # print("line_num %d %d %s" %(line_num, index, line[index:index+(len(source_str_path))]))
            target_str = web_str2url(source_str)
            line = line.replace(source_str_path, target_str, 1)
        
        pic_index =  line.find(picture_head_src)
        if pic_index != -1: # 此行中包含的有要查询的字符串
            #print("line_num %d %d %s" %(line_num, pic_index, line[pic_index:pic_index+(len(picture_head_src))]))
            picture_head = "<!-- Photo: " + web_str2url(source_str) + " -->"
            line = line.replace(picture_head_src, picture_head, 1)

        fp_file_remote.write(line)
        line = fp_file_local.readline()
    fp_file_remote.close()
    fp_file_local.close()
